﻿#include "user-orderPage.h"
#include <QTextEdit>
UserOrderPage::UserOrderPage(database &db, QWidget *parent)
    : QWidget(parent), db(db), userPhoneId(-1), userIdentity(-1)
{
    setupUI();
    setUserInfo(userPhoneId, userIdentity);
}

UserOrderPage::~UserOrderPage()
{
}

void UserOrderPage::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建标题
    titleLabel = new QLabel("我的订单");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 18pt; font-weight: bold; color: #333;");

    // 创建刷新按钮
    refreshButton = new QPushButton("刷新订单");
    refreshButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   border-radius: 5px;"
        "   padding: 8px 15px;"
        "   font-size: 12pt;"
        "}"
        "QPushButton:hover {"
        "   background-color: #45a049;"
        "}"
    );

    // 连接刷新按钮信号
    connect(refreshButton, &QPushButton::clicked, this, &UserOrderPage::loadUserOrders);

    // 创建订单表格
    ordersTable = new QTableWidget(this);
    ordersTable->setColumnCount(8); // 商品名, 商家名, 配送地址, 数量, 下单时间, 状态, 骑手电话, 操作

    // 设置表头
    QStringList headers;
    headers << "商品名称" << "商家名称" << "配送地址" << "数量" << "下单时间" << "订单状态" << "骑手电话" << "操作";
    ordersTable->setHorizontalHeaderLabels(headers);

    // 调整表格样式
    ordersTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ordersTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ordersTable->setAlternatingRowColors(true);
    ordersTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ordersTable->verticalHeader()->setVisible(false);
    ordersTable->setStyleSheet(
        "QTableWidget {"
        "   border: 1px solid #ddd;"
        "   border-radius: 5px;"
        "   background-color: #fff;"
        "}"
        "QTableWidget::item {"
        "   padding: 5px;"
        "}"
        "QTableWidget::item:selected {"
        "   background-color: #e6f7ff;"
        "   color: #000;"
        "}"
        "QHeaderView::section {"
        "   background-color: #f2f2f2;"
        "   padding: 5px;"
        "   border: 1px solid #ddd;"
        "   font-weight: bold;"
        "}"
    );

    // 布局控件
    QHBoxLayout *headerLayout = new QHBoxLayout();
    headerLayout->addWidget(titleLabel, 1);
    headerLayout->addWidget(refreshButton, 0);

    mainLayout->addLayout(headerLayout);
    mainLayout->addWidget(ordersTable);
}

void UserOrderPage::setUserInfo(int phoneId, int userIdentity)
{
    this->userPhoneId = phoneId;
    this->userIdentity = userIdentity;

    // 只有普通用户(userIdentity=1)才能查看此页面
    if (userIdentity == 1) {
        loadUserOrders();
    }
}

void UserOrderPage::loadUserOrders()
{
    // 清空表格内容
    ordersTable->setRowCount(0);

    // 查询用户的所有订单
    QString sql = QString("SELECT o.order_id, c.com_name, b.business_name, o.address, "
                  "o.quantity, o.time_start, cs.status, o.phone, o.cs_id, o.com_id, o.business_id FROM order_c o "
                  "JOIN commodity c ON o.com_id = c.com_id "
                  "JOIN business b ON o.business_id = b.business_id "
                  "JOIN commodity_status cs ON o.cs_id = cs.cs_id "
                  "JOIN user u ON o.user_id = u.user_id "
                  "JOIN phone p ON u.phone_id = p.phone_id "
                  "WHERE p.phone_id = %1 "
                  "ORDER BY o.time_start DESC").arg(userPhoneId);
    
    qDebug() << "userOrderPage-查询用户订单:" << sql;
    QSqlQuery query = db.exec(sql);

    int row = 0;
    while (query.next()) {
        // 获取订单信息
        int orderId = query.value(0).toInt();
        QString comName = query.value(1).toString();
        QString businessName = query.value(2).toString();
        QString address = query.value(3).toString();
        int quantity = query.value(4).toInt();
        QString orderTime = query.value(5).toString();
        QString status = query.value(6).toString();
        QString riderPhone = query.value(7).toString();
        int statusId = query.value(8).toInt();
        int comId = query.value(9).toInt();
        int businessId = query.value(10).toInt();
        
        // 如果骑手电话为空，显示"暂无骑手接单"
        if (riderPhone.isEmpty()) {
            riderPhone = "暂无骑手接单";
        }

        // 添加新行
        ordersTable->insertRow(row);

        // 添加数据到表格
        ordersTable->setItem(row, 0, new QTableWidgetItem(comName));
        ordersTable->setItem(row, 1, new QTableWidgetItem(businessName));
        ordersTable->setItem(row, 2, new QTableWidgetItem(address));
        ordersTable->setItem(row, 3, new QTableWidgetItem(QString::number(quantity)));
        ordersTable->setItem(row, 4, new QTableWidgetItem(orderTime));
        ordersTable->setItem(row, 5, new QTableWidgetItem(status));
        ordersTable->setItem(row, 6, new QTableWidgetItem(riderPhone));
        
        // 添加确认收货按钮
        QPushButton *confirmButton = createConfirmButton(row, orderId, status);
        
        QWidget *buttonWidget = new QWidget();
        QHBoxLayout *buttonLayout = new QHBoxLayout(buttonWidget);
        buttonLayout->addWidget(confirmButton);
        buttonLayout->setAlignment(Qt::AlignCenter);
        buttonLayout->setContentsMargins(0, 0, 0, 0);
        
        // 评论功能：仅已完成订单显示评论按钮
        bool commented = false;
        if (status == "已完成") {
            // 查询是否已评论
            QString commentSql = QString("SELECT COUNT(*) FROM comment WHERE order_id = %1 AND com_id = %2").arg(orderId).arg(comId);
            QSqlQuery commentQuery = db.exec(commentSql);
            if (commentQuery.next() && commentQuery.value(0).toInt() > 0) {
                commented = true;
            }
            QPushButton *commentButton = createCommentButton(row, orderId, comId, comName, commented);
            buttonLayout->addWidget(commentButton);
        }
        ordersTable->setCellWidget(row, 7, buttonWidget);

        row++;
    }

    // 如果没有订单，显示提示
    if (row == 0) {
        QMessageBox::information(this, "提示", "您当前没有订单");
    }
}

QPushButton* UserOrderPage::createConfirmButton(int row, int orderId, const QString &status)
{
    QPushButton *button = new QPushButton("确认收货");
    
    // 设置按钮样式
    if (status == "已送达") {
        button->setEnabled(true);
        button->setStyleSheet(
            "QPushButton {"
            "   background-color: #1890ff;"
            "   color: white;"
            "   border-radius: 3px;"
            "   padding: 5px 10px;"
            "}"
            "QPushButton:hover {"
            "   background-color: #40a9ff;"
            "}"
        );
    } else if (status == "已完成") {
        button->setText("已完成");
        button->setEnabled(false);
        button->setStyleSheet(
            "QPushButton {"
            "   background-color: #52c41a;"
            "   color: white;"
            "   border-radius: 3px;"
            "   padding: 5px 10px;"
            "   opacity: 0.7;"
            "}"
        );
    } else {
        button->setEnabled(false);
        button->setStyleSheet(
            "QPushButton {"
            "   background-color: #d9d9d9;"
            "   color: #ffffff;"
            "   border-radius: 3px;"
            "   padding: 5px 10px;"
            "}"
        );
    }
    
    // 存储订单ID
    button->setProperty("order_id", orderId);
    
    // 连接按钮点击信号
    connect(button, &QPushButton::clicked, this, &UserOrderPage::onConfirmReceiptClicked);
    
    return button;
}

void UserOrderPage::onConfirmReceiptClicked()
{
    // 获取发送信号的按钮
    QPushButton *button = qobject_cast<QPushButton *>(sender());
    if (!button) return;
    
    // 获取订单ID
    int orderId = button->property("order_id").toInt();
    
    // 确认是否确认收货
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认收货",
                                 "确认已收到商品吗？确认后将完成订单。",
                                 QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        if (processOrderCompletion(orderId)) {
            QMessageBox::information(this, "操作成功", "订单已完成，感谢您的使用！");
            // 刷新订单列表
            loadUserOrders();
        } else {
            QMessageBox::warning(this, "操作失败", "确认收货失败，请稍后重试");
        }
    }
}

bool UserOrderPage::processOrderCompletion(int orderId)
{
    // 开始事务
    db.exec("BEGIN TRANSACTION");
    
    try {
        // 1. 查询订单信息
        QString orderSql = QString("SELECT o.com_id, o.quantity, o.business_id, o.rider_id "
                                  "FROM order_c o WHERE o.order_id = %1").arg(orderId);
        QSqlQuery orderQuery = db.exec(orderSql);
        
        if (!orderQuery.next()) {
            throw std::runtime_error("无法获取订单信息");
        }
        
        int comId = orderQuery.value(0).toInt();
        int quantity = orderQuery.value(1).toInt();
        int businessId = orderQuery.value(2).toInt();
        int riderId = orderQuery.value(3).toInt();
        
        // 2. 查询商品价格
        QString commoditySql = QString("SELECT price FROM commodity WHERE com_id = %1").arg(comId);
        QSqlQuery commodityQuery = db.exec(commoditySql);
        
        if (!commodityQuery.next()) {
            throw std::runtime_error("无法获取商品信息");
        }
        
        double price = commodityQuery.value(0).toDouble();
        double totalPrice = price * quantity;
        
        // 3. 更新商家收入
        QString updateBusinessSql = QString("UPDATE business SET income = COALESCE(income, 0) + %1 WHERE business_id = %2")
                                   .arg(totalPrice)
                                   .arg(businessId);
        QSqlQuery updateBusinessQuery = db.exec(updateBusinessSql,"更新商家收入");
        
        if (!updateBusinessQuery.isActive()) {
            throw std::runtime_error("更新商家收入失败");
        }
        
        // 4. 更新商品销量
        QString updateCommoditySql = QString("UPDATE commodity SET number = COALESCE(number, 0)+ %1 WHERE com_id = %2")
                                    .arg(quantity)
                                    .arg(comId);
        QSqlQuery updateCommodityQuery = db.exec(updateCommoditySql,"292-更新商品销量");
        
        if (!updateCommodityQuery.isActive()) {
            throw std::runtime_error("更新商品销量失败");
        }
        
        // 5. 查询配送费并更新骑手收入
        QString deliverySql = QString("SELECT delivery FROM business WHERE business_id = %1").arg(businessId);
        QSqlQuery deliveryQuery = db.exec(deliverySql);
        
        if (!deliveryQuery.next()) {
            throw std::runtime_error("无法获取配送费信息");
        }
        
        double deliveryFee = deliveryQuery.value(0).toDouble();
        
        QString updateRiderSql = QString("UPDATE rider SET Income = COALESCE(Income, 0) + %1 WHERE rider_id = %2")
                                .arg(deliveryFee)
                                .arg(riderId);
        QSqlQuery updateRiderQuery = db.exec(updateRiderSql,"311-更新骑手收入");
        
        if (!updateRiderQuery.isActive()) {
            throw std::runtime_error("更新骑手收入失败");
        }
        
        // 6. 更新订单状态为已完成，并添加完成时间
        QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString updateOrderSql = QString("UPDATE order_c SET cs_id = 8, time_end = '%1' WHERE order_id = %2")
                                .arg(currentTime)
                                .arg(orderId);
        QSqlQuery updateOrderQuery = db.exec(updateOrderSql);
        
        if (!updateOrderQuery.isActive()) {
            throw std::runtime_error("更新订单状态失败");
        }
        
        // 提交事务
        db.exec("COMMIT");
        return true;
    } catch (const std::exception& e) {
        // 回滚事务
        db.exec("ROLLBACK");
        qDebug() << "订单完成处理失败: " << e.what();
        return false;
    }
} 

QPushButton* UserOrderPage::createCommentButton(int row, int orderId, int comId, const QString &comName, bool commented)
{
    QPushButton *btn = new QPushButton(commented ? "已评论" : "去评论");
    btn->setEnabled(!commented);
    connect(btn, &QPushButton::clicked, this, [=]() {
        onCommentClicked(row, orderId, comId, comName);
    });
    return btn;
}

void UserOrderPage::onCommentClicked(int row, int orderId, int comId, const QString &comName)
{
    showCommentDialog(orderId, comId, comName);
}

void UserOrderPage::showCommentDialog(int orderId, int comId, const QString &comName)
{
    QDialog dialog(this);
    dialog.setWindowTitle("评论菜品");
    QVBoxLayout *layout = new QVBoxLayout(&dialog);
    QLabel *label = new QLabel(QString("请对菜品 [%1] 进行评价：").arg(comName), &dialog);
    QTextEdit *edit = new QTextEdit(&dialog);
    edit->setPlaceholderText("请输入评论内容...");
    QHBoxLayout *btnLayout = new QHBoxLayout();
    QPushButton *okBtn = new QPushButton("提交", &dialog);
    QPushButton *cancelBtn = new QPushButton("取消", &dialog);
    btnLayout->addStretch();
    btnLayout->addWidget(okBtn);
    btnLayout->addWidget(cancelBtn);
    layout->addWidget(label);
    layout->addWidget(edit);
    layout->addLayout(btnLayout);
    connect(cancelBtn, &QPushButton::clicked, &dialog, &QDialog::reject);
    connect(okBtn, &QPushButton::clicked, [&]() {
        QString content = edit->toPlainText().trimmed();
        if (content.isEmpty()) {
            QMessageBox::warning(&dialog, "提示", "评论内容不能为空！");
            return;
        }
        // 写入comment表（字段：user_id, com_id, comment, time）
        QString sql = QString("INSERT INTO comment (user_id, com_id, comment, time) VALUES ((SELECT user_id FROM user WHERE phone_id = %1), %2, '%3', datetime('now'))")
            .arg(userPhoneId).arg(comId).arg(content.replace("'", "''"));
        QSqlQuery query = db.exec(sql);
        if (query.isActive()) {
            QMessageBox::information(&dialog, "成功", "评论提交成功！");
            dialog.accept();
            loadUserOrders(); // 刷新订单列表
        } else {
            QMessageBox::warning(&dialog, "错误", "评论提交失败！\n" + query.lastError().text());
        }
    });
    dialog.exec();
} 
